/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package excom;

import bus.MessageBUS;
import dto.MessageDTO;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import ui.MailComposePanel;
import ui.MainForm;
import utils.MsgboxHelper;

/**
 *
 * @author chanhpm
 */
public class OutlookMail extends JPanel{

   
     public enum MailMode{ Inbox, OutBox, Draft, Outbox};

     private MailMode currentMode;
     private JPanel header;
     private JLabel title;
     private JPanel body;
     private JPanel footer;
     private MessageDTO[] messageList;
     private JTable listOfMessage;
     private XTableModel tableModel ;
     
     public  OutlookMail(MailMode modeinquire){
         this.setLayout(new BorderLayout());
         currentMode = modeinquire;
         initComponents();
     }


    /**
     * khoi tao component
     */
     public void initComponents()
     {
         createHeader();
         createBody();
         createFooter();         
     }

     /**
      * tao header
      */
     private void createHeader()
     {
          header = new JPanel(new BorderLayout());
          title = new JLabel(currentMode.name());
          title.setFont(new Font("Arial",Font.BOLD,18));
          title.setForeground(Color.BLUE);
          title.setIcon(new ImageIcon(MainForm.ResourceDir + "mail.gif"));
          header.add(title, BorderLayout.WEST);
          this.add(header, BorderLayout.NORTH);
     }

     /**
      * tao phan than
      */
     private JSplitPane pane;
     private JPanel messageBox;
     private JPanel contentBox;
     private void createBody()
     {
         body = new JPanel(new BorderLayout());
         messageBox = createMessageBox();
         contentBox = createContentBox();
         pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, messageBox, contentBox);
         pane.setResizeWeight(0.5);
         pane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
         pane.setName("mailpane");
         pane.setOpaque(true);
         pane.setDividerSize(5); 
         pane.setEnabled(true);
         this.add(pane, BorderLayout.CENTER);
     }

     /*
      * Box chua danh sach thong diep
      */
    private JPanel createMessageBox()
    {
        JPanel rs = new JPanel(new BorderLayout());
        String[] columnName = {"From","Subject","Received"};
        Object[] obj = {"","",""};
        Vector temp = new Vector();
        temp.add(obj);
        tableModel = new XTableModel(temp, columnName);
        listOfMessage = new JTable( tableModel);
        listOfMessage.setRowHeight(15);
        listOfMessage.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(listOfMessage);
        listOfMessage.setFillsViewportHeight(true);
        listOfMessage.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                viewMessageDetail();
                if(currentMode == MailMode.Draft){
                    if(e.getClickCount() == 2)// double click
                    {
                        MailComposePanel frm = new MailComposePanel();
                        frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        frm.setVisible(true);
                        frm.setMsgId(messageList[listOfMessage.getSelectedRow()].getId());
                        frm.addJBoxListener(new JBoxEventListener() {

                            public void myJBoxEvent(JBoxEvent evt) {
                                if(evt.get_name().equalsIgnoreCase("sendmessage"))
                                {
                                    MsgboxHelper.inform("Message sent");
                                    refresh();
                                }
                                else// update
                                {
                                    MsgboxHelper.inform("Message saved");
                                    refresh();
                                }
                                 repaint();
                                 validate();

                            }
                        });
                    }
                }
            }
        });
         rs.add(scrollPane, BorderLayout.CENTER);
         refresh();
         return rs;
    }

    private void viewMessageDetail(){
        int i = listOfMessage.getSelectedRow();
        if(i > -1){
            MessageDTO msg= messageList[i];
            String msgDetail = "<html><body>";
            msgDetail += "<h2>" + msg.getSubject()+"</h2>";           
            msgDetail += "<font color=#0066FF>From</font>" + " :" + msg.getFrom() + "<br/>";
            msgDetail += "<font color=#0066FF>Date</font>" + " :" + msg.getSentDate() + "<br/>";
            msgDetail += "<font color=#0066FF>To</font>" + "   :" + msg.getTo() + "<br/>";
            msgDetail += "<hr><br>";
            msgDetail += msg.getBody();
            msgDetail += "</body></html>";
            messageText.setText(msgDetail);

        }
    }
    private JLabel messageText;
    //private TextField messageText;
    private JPanel createContentBox(){
        JPanel rs = new JPanel(new BorderLayout());       
        messageText = new JLabel();
        messageText.setBackground(Color.WHITE);
        messageText.setFont(new Font("Arial", Font.PLAIN,12));       
        JScrollPane temp = new JScrollPane(messageText);
        rs.add(temp);
        //rs.add(messageText);
        temp.setAutoscrolls(true);
        rs.setBackground(Color.WHITE);
        rs.repaint();
        return rs;
    }


     /**
      * tao footer
      */
     private void createFooter(){
         footer = new JPanel(new BorderLayout());
         this.add(footer, BorderLayout.SOUTH);
     }
     /**
      * Doi che do xem mail: mail den, mail di, mail nhap
      * @param modeinquire
      * @param showText
      */
     public void switchMode(MailMode modeinquire){
         currentMode = modeinquire;
        
         switch(currentMode){
             case Inbox:                  
                 changeColumnHeader(0, "From");
                 changeColumnHeader(2, "Received");
                 title.setText(currentMode.name());
                 break;
             case OutBox:
                  changeColumnHeader(0, "To");
                  changeColumnHeader(2, "Sent");
                  title.setText(currentMode.name());
                 break;
             case Draft:
                  changeColumnHeader(0, "To");
                  changeColumnHeader(2, "Sent");
                  title.setText(currentMode.name());
                 break;
         }        
     }

     public void changeViewState(){
        if(pane.getOrientation() == JSplitPane.HORIZONTAL_SPLIT)
            pane.setOrientation(JSplitPane.VERTICAL_SPLIT);
        else
            pane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);     
     }
     public void refresh()
     {
        //if(!type.equalsIgnoreCase(currentMode.name()))
          //      return;
        tableModel.clearallRow();
        ArrayList<MessageDTO> list = new ArrayList<MessageDTO>();
        MessageBUS bus = new MessageBUS();
        
        list = bus.getMessageFromType(currentMode.name());
        Vector v = new Vector();
        messageList = new MessageDTO[list.size()];
        for(int i = 0; i < list.size(); i++)
        {
            MessageDTO c = list.get(i);
            if (currentMode == MailMode.Inbox)
            {
                Object[] temp = {c.getFrom(),c.getSubject(),c.getSentDate()};
                v.add(temp);
            }
            else
            {
                Object[] temp = {c.getTo(),c.getSubject(),c.getSentDate()};
                v.add(temp);
            }
            messageList[i] = c;
        }
        if(v.size() > 0)
            tableModel.fillData(v);
     }

     private void changeColumnHeader(int index, String newValue)
     {
         listOfMessage.getColumnModel().getColumn(index).setHeaderValue(newValue);
     }
     public MessageDTO getMsgSelected(){
         int i = listOfMessage.getSelectedRow();
         if(i == -1)
             return null;
         return messageList[i];
     }
}
